<?php
/**
 * Created by PhpStorm.
 * User: 盛茂国
 * Tel: 18394333958
 * Date: 2020/6/2
 * Time: 10:31
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use ChuanglanSmsHelper\ChuanglanSmsApi;
use fast\Random;
use think\Hook;
use think\Loader;
use think\Request;

/**
 * 手机短信接口
 */
class Sms extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 发送验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     */
    public function send()
    {
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");
        $event = $event ? $event : 'register';

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        if (!Hook::get('sms_send')) {
            $this->error(__('请在后台插件管理安装短信验证插件'));
        }
        $ret = Smslib::send($mobile, null, $event);
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
        }
    }

    /**
     * 检测验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     * @param string $captcha 验证码
     */
    public function check()
    {
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");
        $event = $event ? $event : 'register';
        $captcha = $this->request->request("captcha");

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        $ret = Smslib::check($mobile, $captcha, $event);
        if ($ret) {
            $this->success(__('成功'));
        } else {
            $this->error(__('验证码不正确'));
        }
    }
    //发送注册短信
    public function nsend(Request $request){
        if (!$request->isPost()) return;
        header("Content-type:text/html; charset=UTF-8");
        //Loader::import('ChuanglanSmsHelper\ChuanglanSmsApi','extend/');
        $mobile=$request->param('mobile');
        $clapi  = new ChuanglanSmsApi();
        $code = mt_rand(100000,999999);
        $db=db('sms');
        if(!preg_match('/^1[3,5,6,7,8,9]\d{9}/',$mobile)){
            return json(['code'=>400,'msg'=>'电话号码非法']);
        }
        $issend=$db->where('mobile',$mobile)->order('id desc')->find();
        $result=null;
        $num=$issend['times']+1;
        if(!$issend ){
            $result = $clapi->sendSMS($mobile,'尊敬的用户您好，欢迎注册【绮愿】小程序，您的注册验证码是'.$code  );
            $data=[
                'mobile'=>$mobile,
                'code'=>$code,
                'createtime'=>time(),
                'ip'=>$request->ip(),
                'times'=>$issend['times']+1
            ];
            $db->data($data)->insert();
        }else if( time()-$issend['createtime']>300  && $issend['times']<5 ){
            $result = $clapi->sendSMS($mobile,'尊敬的用户您好，欢迎注册【绮愿】小程序，您的注册验证码是'.$code );
            $data=[
                'mobile'=>$mobile,
                'code'=>$code,
                'createtime'=>time(),
                'ip'=>$request->ip(),
                'times'=>$num
            ];
            $db->data($data)->insert();
        }
        if(!is_null(json_decode($result))){
            $output=json_decode($result,true);
            if(isset($output['code'])  && $output['code']=='0'){
                return json(['code'=>200,'msg'=>'发送成功','data'=>$output['code']]);
            }else{
                //echo $output['errorMsg'];
                return json(['code'=>400,'msg'=>$output['errorMsg']]);
            }
        }else{
            //echo $result;
            return json(['code'=>500,'msg'=>'发送短信服务器异常']);
        }
    }
    //发送点赞衣服到店短信
    public function notice($mobile,$shopname,$storename){
        header("Content-type:text/html; charset=UTF-8");
        //Loader::import('ChuanglanSmsHelper\ChuanglanSmsApi','extend/');
        $clapi  = new ChuanglanSmsApi();

        if(!preg_match('/^1[3,5,6,7,8,9]\d{9}/',$mobile)){
            return json(['code'=>400,'msg'=>'电话号码非法']);
        }
        $msg='尊贵的【绮愿】用户您好，您的收藏过的【'.$shopname.'】衣服到店了,请光临【'.$storename.'】领取衣服';
        $result = $clapi->sendSMS($mobile,$msg  );

        $db=db('notice');

        if(!is_null(json_decode($result))){
            $output=json_decode($result,true);
            if(isset($output['code'])  && $output['code']=='0'){
                $data=[
                    'mobile'=>$mobile,
                    'createtime'=>time(),
                    'event'=>$msg,
                    'success'=>1
                ];
                $db->data($data)->insert();
                return json(['code'=>200,'msg'=>'发送成功','data'=>$output['code']]);
            }else{
                $data=[
                    'mobile'=>$mobile,
                    'createtime'=>time(),
                    'event'=>$msg,
                    'success'=>0
                ];
                $db->data($data)->insert();
                return json(['code'=>400,'msg'=>$output['errorMsg']]);
            }
        }else{
            $data=[
                'mobile'=>$mobile,
                'createtime'=>time(),
                'event'=>$msg,
                'success'=>0
            ];
            $db->data($data)->insert();
            return json(['code'=>500,'msg'=>'发送短信服务器异常']);
        }
    }
    public function minilogin(Request $request){
        $mobile=$request->param('mobile');
        $password=$request->param('password');
        if(!$request->isPost()) return;
        $user=db('user')->where('mobile',$mobile)->find();
        $auth=new \app\common\library\Auth();
        if($user['password']===$auth->getEncryptPassword($password,Random::alnum())){
            return json(['code'=>200,'msg'=>'登录成功','data'=>$user]);
        }else{
            return json(['code'=>400,'msg'=>'登录失败']);
        }
    }

    public function ticket(Request $request){
        if($request->isPost()){
            $mobile=$request->param('mobile');
            $catcoin=db('user')->where('mobile','=',$mobile)->value('catcoin');
            if(empty($catcoin) || $catcoin <1){
                return json(['status'=>400,'msg'=>'您没有余额，无法领取衣服，请分享会员，或者充值兑换猫币']);
            }else{
                header("Content-type:text/html; charset=UTF-8");
                Loader::import('ChuanglanSmsHelper\ChuanglanSmsApi','extend/');

                $clapi  = new ChuanglanSmsApi();
                $code = mt_rand(100000,999999);
                $db=db('ticket');

                if(!preg_match('/^1[3,5,7,8]\d{9}/',$mobile)){
                    return json(['code'=>400,'msg'=>'电话号码非法']);
                }
                $issend=$db->where('mobile',$mobile)->order('id desc')->find();

                $result=null;
                $num=$issend['times']+1;

                if(!$issend ){
                    $result = $clapi->sendSMS($mobile,'【庄浪融媒】您好，您的衣服领取凭证验证码是，请妥善保管该验证码，该验证码3天后失效，如果失效请重新到小程序端获取新的验证码'.$code  );
                    $data=[
                        'mobile'=>$mobile,
                        'code'=>$code,
                        'createtime'=>time(),
                        'ip'=>$request->ip(),
                        'times'=>$issend['times']+1,
                        'event'=>'领取凭证'
                    ];
                    $db->data($data)->insert();
                }else if( time()-$issend['createtime']>3600*24*3  && $issend['times']<5 ){
                    $result = $clapi->sendSMS($mobile,'【庄浪融媒】您好，您的衣服领取凭证验证码是，请妥善保管该验证码，该验证码3天后失效，如果失效请重新到小程序端获取新的验证码'.$code );
                    $data=[
                        'mobile'=>$mobile,
                        'code'=>$code,
                        'createtime'=>time(),
                        'ip'=>$request->ip(),
                        'times'=>$num,
                        'event'=>'领取凭证'
                    ];
                    $db->data($data)->insert();
                }

                if(!is_null(json_decode($result))){
                    $output=json_decode($result,true);
                    if(isset($output['code'])  && $output['code']=='0'){
                        return json(['code'=>200,'msg'=>'发送成功','data'=>$output['code']]);
                    }else{
                        //echo $output['errorMsg'];
                        return json(['code'=>400,'msg'=>$output['errorMsg']]);
                    }
                }else{
                    //echo $result;
                    return json(['code'=>500,'msg'=>'发送短信未过期']);
                }
            }
        }else{
            return json(['status'=>400,'非法请求']);
        }

    }
}
